package com.csair.platform.cit.service.controller;


import com.csair.invoice.common.base.exception.PlatformException;
import com.csair.invoice.common.base.vo.JsonResult;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice
public class GlobalExceptionHandler {

	/**
	 * 日志服务类
	 */
	private Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	
	
	@ResponseStatus(code=HttpStatus.OK)
	@ExceptionHandler(PlatformException.class)
    public JsonResult handleException(PlatformException e) {
		log.error("全局异常处理捕捉到业务异常：", e);
	    return JsonResult.fail(e);
    }
	
	@ResponseStatus(code=HttpStatus.INTERNAL_SERVER_ERROR)
	@ExceptionHandler(Exception.class)
    public JsonResult handleException(Exception e) {
		log.error("系统异常：", e);
		return JsonResult.fail(500, e.getMessage());
    }
	
	@ResponseStatus(code=HttpStatus.INTERNAL_SERVER_ERROR)
	@ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult handleArgumentException(MethodArgumentNotValidException e) {
		log.error("系统异常：", e);
		List<FieldError> errors = e.getBindingResult().getFieldErrors();
		StringBuffer sb = new StringBuffer("参数格式错误：");
	    for (int i = 0; i < errors.size(); i++) {
	    	FieldError er = errors.get(i);
	    	sb.append(er.getField()).append(":").append(er.getDefaultMessage()).append(",");
		}

		return JsonResult.fail(500, sb.toString());
    }
}
